﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DriveBeamEditor.Controls.General.Data
{
    public class TreeNode
    {
        #region Fields

        private TreeNode _parent;
        private readonly TreeNodeCollection _children;

        public event EventHandler<TreeNode> ParentChanged;
        public event EventHandler<TreeNode> ChildAdded;
        public event EventHandler<TreeNode> ChildRemoved;

        #endregion

        #region Properties

        public string Name { get; private set; }

        public string Path
        {
            get
            {
                return string.Format("{0}{1}", (Parent != null ? Parent.Path + "." : string.Empty), Name);
            }
        }

        public object Data { get; set; }

        public TreeNode Parent
        {
            get { return _parent; }
            set
            {
                if (_parent == value) return;

                _parent = value;

                if (ParentChanged != null)
                    ParentChanged(this, value);
            }
        }

        public TreeNodeCollection Children { get { return _children; } }

        #endregion

        #region CTORs

        public TreeNode(string name, object data)
        {
            _children = new TreeNodeCollection(this);
            _children.TreeNodeAdded += (s, e) =>
            {
                if (ChildAdded != null) ChildAdded(this, e);
            };
            _children.TreeNodeRemoved += (s, e) =>
            {
                if (ChildRemoved != null) ChildRemoved(this, e);
            };

            ParentChanged += (s, e) =>
            {
                if (Parent != null) Parent.ParentChanged(s, e);
            };
            ChildAdded += (s, e) =>
            {
                if (Parent != null) Parent.ChildAdded(s, e);
            };
            ChildRemoved += (s, e) =>
            {
                if (Parent != null) Parent.ChildRemoved(s, e);
            };

            Name = name;
            Data = data;
        }

        public TreeNode(string name, object data, TreeNode parent)
            : this(name, data)
        {
            Parent = parent;
        }

        #endregion
    }
}
